import pygame
import random
# 初始化Pygame
pygame.init()

# 设置屏幕
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# 玩家飞机
player_size = 50
player_pos = [screen_width // 2, screen_height - 2 * player_size]
player_speed = 10

# 敌人飞机
enemy_size = 50
enemy_pos = [random.randint(0, screen_width - enemy_size), 0]
enemy_list = [enemy_pos]
enemy_speed = 5

# 子弹
bullet_size = 10
bullet_pos = []
bullet_speed = 10

# 游戏状态
game_over = False
score = 0

# 字体
font = pygame.font.SysFont("monospace", 35)

# 创建敌人
def drop_enemies(enemy_list):
    delay = random.random()
    if len(enemy_list) < 10 and delay < 0.1:
        x_pos = random.randint(0, screen_width - enemy_size)
        y_pos = 0
        enemy_list.append([x_pos, y_pos])

# 绘制敌人
def draw_enemies(enemy_list):
    for enemy_pos in enemy_list:
        pygame.draw.rect(screen, RED, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))

# 更新敌人位置
def update_enemy_positions(enemy_list, score):
    for idx, enemy_pos in enumerate(enemy_list):
        if enemy_pos[1] >= 0 and enemy_pos[1] < screen_height:
            enemy_pos[1] += enemy_speed
        else:
            enemy_list.pop(idx)
            score += 1
    return score

# 检测碰撞
def collision_check(enemy_list, player_pos):
    for enemy_pos in enemy_list:
        if detect_collision(enemy_pos, player_pos):
            return True
    return False

# 检测单个碰撞
def detect_collision(player_pos, enemy_pos):
    p_x, p_y = player_pos
    e_x, e_y = enemy_pos

    if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x + enemy_size)):
        if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y + enemy_size)):
            return True
    return False

# 主循环
clock = pygame.time.Clock()
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

        if event.type == pygame.KEYDOWN:
            x, y = player_pos
            if event.key == pygame.K_LEFT:
                x -= player_speed
            elif event.key == pygame.K_RIGHT:
                x += player_speed
            player_pos = [x, y]

    screen.fill(BLACK)

    # 生成敌人
    drop_enemies(enemy_list)
    score = update_enemy_positions(enemy_list, score)

    # 绘制玩家
    pygame.draw.rect(screen, WHITE, (player_pos[0], player_pos[1], player_size, player_size))

    # 绘制敌人
    draw_enemies(enemy_list)

    # 检测碰撞
    if collision_check(enemy_list, player_pos):
        game_over = True
        break

    # 显示分数
    text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(text, (10, 10))

    pygame.display.update()
    clock.tick(30)

pygame.quit()

